import React, { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Button, Drawer, Flex, Form, Input, Radio, message, Select } from "antd";
import UploadItem from '../../../Components/UploadItem';
import { ACCEPT_TYPE, SYSCODE, CONFIG_ITEM_KEYS } from '../../../../utils/constant';
import { apiSysDictSelect } from '../../../../services/common';
import { apiMSDModuleAdd, apiMSDModuleEdit, apiMSDModuleNameCheck, apiMSDModuleView } from '../../../../services/masterData/module';
import { getUserName, transformArray } from '../../../../utils/commonUtil';

const EditModal = ({
  openDrawer,
  setOpenDrawer,
  editSucessFn,
  editType,
  recordData,
}) => {
  const { t } = useTranslation();
  const [form] = Form.useForm();
  const { TextArea } = Input;
  const [moduleName, setModuleName] = useState(recordData?.moduleName || '');
  const [callTypeList, setCallTypeList] = useState([]);
  const [moduleList, setModuleList] = useState([]);
  const [callType, setCallType] = useState(recordData?.callMethod || '');
  const [initialData, setInitialData] = useState();
  const [fileList, setFileList] = useState([]);
  const { PY } = ACCEPT_TYPE;
  const { MODULE_CALL_METHOD, MODULE } = CONFIG_ITEM_KEYS;

  const moduleNameChange = (value) => {
    setModuleName(value);
  };
  const callTypeChange = (e) => {
    console.log(e?.target?.value);
    setCallType(e?.target?.value);
  };
  const apiMSDModuleSaveSync = async (params) => {
    const { data } = editType === 'edit' ? await apiMSDModuleEdit(params) : await apiMSDModuleAdd(params);
    if (data?.code === 200) {
      message.success(t('common.saveSuccess'));
      setOpenDrawer(false);
      editSucessFn();
    }
  };
  const saveClickHandle = () => {
    const params = form?.getFieldsValue();
    params.userId = getUserName();
    params.analyticalMethod = params?.analyticalMethod?.trim();
    if (editType === 'edit') {
      params.moduleAnalyticalMethodId = recordData.moduleAnalyticalMethodId;
    };
    form.validateFields().then(() => {
      apiMSDModuleSaveSync(params);
    }, () => {
      return false;
    });
  };
  const initModalData = async () => {
    const params = {
      sysCode: SYSCODE,
      dictCodes: [MODULE_CALL_METHOD, MODULE]
    }
    const { data } = await apiSysDictSelect(params);
    setCallTypeList(data?.data?.[MODULE_CALL_METHOD]);
    console.log(transformArray(data?.data?.[MODULE]));
    setModuleList(transformArray(data?.data?.[MODULE]));
    let initData = {
      MODULE_CALL_METHOD: data?.data?.[MODULE_CALL_METHOD]?.[0]
    };
    if (editType !== 'new') {
      let resData = await apiMSDModuleView({ id: recordData.moduleAnalyticalMethodId });
      const detialData = resData?.data?.data?.item;
      detialData.request = detialData.request?.value ? JSON.parse(detialData.request?.value) : {};
      detialData.response = detialData.response?.value ? JSON.parse(detialData.response?.value) : {};
      initData = {
        ...initData,
        ...detialData
      };
      if (detialData?.callMethod === 'Script') {
        setFileList([
          {
            uid: initData?.attachmentUrl,
            name: initData?.attachmentUrl,
            status: 'done',
            url: initData?.attachmentUrl,
            attachmentUrl: initData?.attachmentUrl
          }
        ]);
      };
    };
    setInitialData(initData);
  };

  useEffect(() => {
    initModalData();
  }, []);

  return (
    <>
      {
        initialData &&
        <Drawer
          title={t(`common.${editType}`)}
          footer={
            <Flex justify='flex-end'>
              <Button type="primary" onClick={saveClickHandle} disabled={editType === 'view'}>{t('common.save')}</Button>
            </Flex>
          }
          placement="right"
          onClose={() => setOpenDrawer(false)}
          open={openDrawer}
          width={600}>
          <Form form={form} labelCol={{ span: 24 }} wrapperCol={{ span: 24 }} initialValues={initialData} disabled={editType === 'view'}>
            <Form.Item name="moduleName" label={t('common.module')}
              rules={[
                {
                  required: true,
                  message: t('common.selectRequired'),
                }
              ]}>
              <Select placeholder={t('common.pleaseSelect')} allowClear options={moduleList} onChange={moduleNameChange} />
            </Form.Item>
            <Form.Item name="callMethod" label={t('common.callMethod')} rules={[{ required: true, message: t('common.inputRequired'), }]}>
              <Radio.Group onChange={callTypeChange}>
                {
                  callTypeList && callTypeList.map((item) => <Radio key={item} value={item}>{item}</Radio>)
                }
              </Radio.Group>
            </Form.Item>
            <Form.Item name="analyticalMethod" label={t('masterData.analyticalMethod')}
              rules={[
                { required: true, message: t('common.inputRequired'), },
                {
                  validator: async (_, value) => {
                    if (value && value?.trim() !== '') {
                      const { data } = await apiMSDModuleNameCheck({ analyticalMethod: value, moduleName: form?.getFieldsValue()?.moduleName });
                      if (data?.data?.count > 0) {
                        return Promise.reject(t('masterData.analyticalMethodNameDuplicate'));
                      } else {
                        return Promise.resolve();
                      }
                    }
                  }
                }
              ]}
            >
              <Input placeholder={t('common.pleaseEnter')} />
            </Form.Item>
            {
              callType === 'Service' &&
              <>
                <Form.Item name="url" label={t('common.url')} rules={[{ required: true, message: t('common.inputRequired'), }]}>
                  <Input placeholder={t('common.pleaseEnter')} />
                </Form.Item>
                <Form.Item name="request" label={t('common.request')} rules={[{ required: true, message: t('common.inputRequired'), }]}>
                  <TextArea placeholder={t('common.pleaseEnter')} />
                </Form.Item>
                <Form.Item name="response" label={t('common.response')} rules={[{ required: true, message: t('common.inputRequired'), }]}>
                  <TextArea placeholder={t('common.pleaseEnter')} />
                </Form.Item>
              </>
            }

            {
              callType === 'Script' &&
              <Form.Item name="attachmentUrl" label={t('common.attachment')} rules={[{ required: true, message: t('common.inputRequired'), }]}>
                <UploadItem
                  maxCount={1}
                  btnText={t('masterData.uploadPy')}
                  acceptType={PY}
                  uploadModule='module'
                  uploadName={moduleName}
                  uploadUpdateFn={(data) => {
                    form?.setFieldValue('attachmentUrl', data?.[0]?.attachmentUrl);
                  }}
                  disabled={(!moduleName && editType !== 'view') || editType === 'view'}
                  fileListData={fileList}
                />
              </Form.Item>
            }
            <Form.Item name="remark" label={t('common.remarks')}>
              <TextArea placeholder={t('common.pleaseEnter')} />
            </Form.Item>
          </Form>
        </Drawer>
      }
    </>
  )
};

export default EditModal;